package com.zhx.real.mybatisplus.business;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.zhx.real.mybatisplus.util.AddPojoException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.Serializable;
import java.util.List;

/**
 * @author zhanghaixuan
 */
public class TreeController<T extends TreeEntity, ID extends Serializable> {

    @Autowired
    private IService<T> service;

    public IService<T> getModelService() {
        return service;
    }

    /**
     * 获取所有的数据
     * @return 返回前端json数据
     */
    @GetMapping("/getList")
    public List<T> getList(T pojo){
        List<T> list = service.list(Wrappers.query(pojo));
        return list;
    }

    @GetMapping("/getTree")
    public List<T> getTree(T pojo){
        List<T> list = service.list(Wrappers.query(pojo));
        List<T> ts = TreeEntityUtil.buildByRecursive(list, null);
        return ts;
    }

    /**
     * 分页查询
     * @param pojo  分页的实体类
     * @return 返回前端json数据
     */
    @GetMapping("/getPageList")
    public IPage<T> getPageList(Page page, T pojo){
        IPage<T> records = service.page(page, Wrappers.query(pojo));
        return records;
    }


    /**
     * 增加一条数据
     * @param pojo 任意一个类型的实体类
     * @return 返回前端json数据
     */
    @PostMapping("/addData")
    public T addData(@RequestBody T pojo){
        boolean flag = service.save(pojo);
        if(flag){
            return pojo;
        }else{
            throw new AddPojoException("添加失败");
        }
    }


    /**
     * 根据id修改一条数，数据中必须有主键id字段
     * @param pojo 任意实体类
     * @return 返回前端json数据
     */
    @PostMapping("/updateById")
    public T updateById(@RequestBody T pojo){
        boolean flag = service.updateById(pojo);
        if(flag){
            return pojo;
        }else{
            throw new AddPojoException("修改失败");
        }
    }


    /**
     * 根据id删除一条数据
     * @param id 传入的id值
     * @return 返回前端json数据
     */
    @PostMapping("/deleteById")
    public boolean delete(@RequestParam("id") String id){
        boolean flag = service.removeById(id);

        return flag;
    }
}
